<?php
defined('_JEXEC') or die;
class DatafeedController extends JControllerLegacy{

	function display($cachable = false, $urlparams = false){
		$task=JRequest::getvar( 'method', '');
		$user=JFactory::getUser();
if($user->groups[2]==2 AND $task!="list") die;
		switch ($task){
			case "add":
			$startTime=JRequest::getVar('CalendarStartTime', '', 'post');
			$endTime=JRequest::getVar('CalendarEndTime', '', 'post');
			$title=JRequest::getVar('CalendarTitle', '', 'post');
			$isAllDay=JRequest::getInt('IsAllDayEvent', 0, 'post');
$ret = $this->addCalendar( $startTime, $endTime, $title, $isAllDay);
break;
			case "list":
			$showDate=JRequest::getVar('showdate', '', 'post');
			$viewtype=JRequest::getVar('viewtype', '', 'post');
$ret = $this->listCalendar( $showDate, $viewtype);
break;
			case "edit":
			JLoader::import("edit",JPATH_COMPONENT);
break;
			case "update":
			$cID=JRequest::getInt('calendarId', 0, 'post');
			$startTime=JRequest::getVar('CalendarStartTime', '', 'post');
			$endTime=JRequest::getVar('CalendarEndTime', '', 'post');
$ret = $this->updateCalendar( $cID, $startTime, $endTime);
break;
			case "remove":
			$cID=JRequest::getInt('calendarId', 0, 'post');
$ret = $this->removeCalendar( $_POST["calendarId"]);
break;
			case "adddetails":
			$cID=JRequest::getInt('id', 0, 'get');
			$sDate=JRequest::getVar('stpartdate', '', 'post');
			$sTime=JRequest::getVar('stparttime', '', 'post');
			$eDate=JRequest::getVar('etpartdate', '', 'post');
			$eTime=JRequest::getVar('etparttime', '', 'post');
			$subject=JRequest::getVar('Subject', '');
			$isAllDay=JRequest::getInt('IsAllDayEvent', 0, 'post');
			$desc=JRequest::getVar('Description', '');
			$location=JRequest::getVar('Location', '');
			$color=JRequest::getVar('colorvalue', '');
			$zone=JRequest::getVar('timezone', '');
			$st = "$sDate $sTime";
			$et = "$eDate $eTime";
			if($cID){
$ret = $this->updateDetailedCalendar ($cID, $st, $et,
		$subject, $isAllDay ? 1:0, $desc,
		$location, $color, $zone);
}else{$color=14;
$ret = $this->addDetailedCalendar($st, $et,					
		$subject, $isAllDay ? 1:0, $desc,
		$location, $color, $zone);
}		
break;
		}

		if($ret)
			echo json_encode($ret);die;
	}

	private function js2PhpTime($date){
		if(strpos($date, '-')){
			if(preg_match('@(\d+)-(\d+)-(\d+)\s+(\d+):(\d+)@', $date, $matches)==1)
				return mktime($matches[4], $matches[5], 0, $matches[2], $matches[3], $matches[1]);
			else if(preg_match('@(\d+)-(\d+)-(\d+)@', $date, $matches)==1){
				return mktime(0, 0, 0, $matches[2], $matches[3], $matches[1]);
		}
		}else if(preg_match('@(\d+)/(\d+)/(\d+)\s+(\d+):(\d+)@', $date, $matches)==1){
				return mktime($matches[4], $matches[5], 0, $matches[1], $matches[2], $matches[3]);
		}else if(preg_match('@(\d+)/(\d+)/(\d+)@', $date, $matches)==1){
			return mktime(0, 0, 0, $matches[2], $matches[3], $matches[1]);
		}else
			return mktime();
	}

	private function php2MySqlTime($date){
		//echo '<pre>',print_r(date("Y-m-d h:i:00", $date)),'</pre>';die;
		return date("Y-m-d H:i:00", $date);
	}

	private function js2MySqlTime($date){
		return $this->php2MySqlTime($this->js2PhpTime($date));
	}


	private function mySql2PhpTime($sqlDate){
		$arr = date_parse($sqlDate);
		return mktime($arr["hour"],$arr["minute"],$arr["second"],$arr["month"],$arr["day"],$arr["year"]);
	}

	private function php2JsTime($date){
		return date("m/d/Y H:i", $date);
	}

	private function mySql2JsTime($date){
		return $this->php2JsTime($this->mySql2PhpTime($date));
	}

	function addCalendar($st, $et, $sub, $aday){
		$db = JFactory::getDBO();
		$cID=JRequest::getInt('id', 0);
		$db->setQuery("INSERT INTO `#__jqcalendar` (`id_student`, `subject`, `starttime`, `endtime`, `isalldayevent`, `color`)VALUES(".
			$cID.",".
			$db->quote($sub).",".
			$db->quote($this->js2MySqlTime($st)).",".
			$db->quote($this->js2MySqlTime($et)).",".
			$db->quote($aday).",".
			"14".//new notification default color
		")");
		//echo '<pre>',print_r($db),'</pre>';die;
		$res=$db->execute();

		if($res)
			return array("IsSuccess"=>true,"Msg"=>'Quickadd success',"Data"=>$db->insertid());
		else
			return array("IsSuccess"=>false,"Msg"=>$db->getErrorMsg());
	}

	function listCalendar($day, $type){
		$time = $this->js2PhpTime($day);
		//echo $time . "+" . $type;die;
		switch($type){
			case "month":
			$st = mktime(0, 0, 0, date("m", $time), 1, date("Y", $time));
			$et = mktime(0, 0, -1, date("m", $time)+1, 1, date("Y", $time));
			break;
			case "week":
			//suppose first day of a week is monday 
			$monday =  date("d", $time) - date('N', $time) + 1;
			//echo $monday;die;
			$st = mktime(0,0,0,date("m", $time), $monday, date("Y", $time));
			$et = mktime(0,0,-1,date("m", $time), $monday+7, date("Y", $time));
			break;
			case "day":
			$st = mktime(0, 0, 0, date("m", $time), date("d", $time), date("Y", $time));
			$et = mktime(0, 0, -1, date("m", $time), date("d", $time)+1, date("Y", $time));
			break;
		}
		//echo $st . "--" . $et;
		return $this->listCalendarByRange($st, $et);
	}

	function listCalendarByRange($sd, $ed){

		$uid=JRequest::getInt('id',0);
		$ret = array("events"=>array(),"issort"=>true,
			"start"=>$this->php2JsTime($sd),
			"end"=>$this->php2JsTime($ed),
			"error"=>NULL);

		$db = JFactory::getDBO();
		$db->setQuery("SELECT registerDate FROM `#__users`
		WHERE id=$uid");
		$res=$db->loadResult();
		$res=$this->mySql2PhpTime($res);
		$monday =  date("d", $res) - date('N', $res) + 1;
		$res = mktime(0,0,0,date("m", $res), $monday, date("Y", $res));//whatever day, goto Monday in current week

		$weekNum=round(($sd-$res)/604800);//week count from registerDate to StartRange

		$tmp=$db->quote($this->php2MySqlTime($sd));
		$res=$db->quote($this->php2MySqlTime($ed));
		$db->setQuery("SELECT * FROM `#__jqcalendar`
		WHERE id_student=$uid AND type=0 AND StartTime < ".$db->quote($this->php2MySqlTime($ed)));
		$res=$db->loadObjectList();
/*
RecurringRule structure
array(
	weekdays=>array(),
	weeks=>array(),
	data=>array(
		[x]=>array(
			[xx]=>xxx
		),
		[y]=>array(
			[yy]=>yyy
		)
	)
)
data is map by weeks & weekdays, contain invidual data for clones
*/

//[V] student only see items until now
		$isStu=JFactory::getUser();
		$isStu=$isStu->groups[2] ? 1 : 0;
		$now=time();
//
		if($res)
			foreach($res as $row){

				$xTime=explode(" ", $row->StartTime);$xTime=trim($xTime[1]);
				$row->StartTime=$this->mySql2PhpTime($row->StartTime);
				$row->EndTime=$this->mySql2PhpTime($row->EndTime);

			if($row->StartTime >= $sd AND $row->StartTime <= $ed)
				if(!$isStu OR $row->StartTime <= $now)//not student or student and only till now 
					$ret['events'][] = array(
						$row->Id+0,
						$row->Subject,
						$this->php2JsTime($row->StartTime),
						$this->php2JsTime($row->EndTime),
						$row->IsAllDayEvent+0,
						0, //more than one day event
						//$row->InstanceType,
						0,//Recurring event,
						($row->Color==10 ? 10 : ($row->Color==2 ? 1 : 0)),//NEW color
						1,//editable
						$row->Location,
						''//$attends
					);

			if($row->RecurringRule){//$ed time is 23:59

				$row->RecurringRule=json_decode($row->RecurringRule);
				foreach($row->RecurringRule->weeks as $v){
					if($weekNum==$v){
						foreach($row->RecurringRule->weekdays as $vv){

							$sclone=strtotime(date("Y-m-d ".$xTime, $sd)."+".($vv-1)." days");
							if($sclone > $row->StartTime){
								if(!$isStu OR $sclone <= $now)
	$ret['events'][] = array(
	$row->Id+0,
	$row->Subject,
	$this->php2JsTime($sclone),
	$this->php2JsTime($sclone+3600),
	$row->IsAllDayEvent+0,
	0, //more than one day event
	1,//Recurring event,
	(isset($row->RecurringRule->data->$v->$vv) ? ($row->RecurringRule->data->$v->$vv==2 ? 1 : 10) : 0),//color, NEW
	0,//editable
	$row->Location,
	''
	);
							}
						}
					break;
					}
				}
			}
			///checking*/
			}
		else
			$ret['error']=$db->getErrorMsg()?:NULL;

		return $ret;
	}

	function updateCalendar($cID, $st, $et){
		$db = JFactory::getDBO();
		$db->setQuery("UPDATE `#__jqcalendar` SET".
			" `starttime`='" . $this->js2MySqlTime($st) . "'," .
			" `endtime`='" . $this->js2MySqlTime($et) . "'" .
			" WHERE `id`=" . $cID);
		$res=$db->execute();

		if($res)
				return array("IsSuccess"=>true,"Msg"=>'Succefully');
			else
				return array("IsSuccess"=>false,"Msg"=>$db->getErrorMsg());
	}

function addDetailedCalendar($st, $et, $sub, $ade, $dscr, $loc, $color, $tz){
	$isrepeat=JRequest::getInt('repeat', 0);
	$weekdays=JRequest::getVar('wd', array());
	$weekdays=array_map('intval',$weekdays);
	$weeks=JRequest::getVar('w', array());
	$weeks=array_map('intval',$weeks);

	if($isrepeat){
		$rules=json_encode(array("weekdays"=>$weekdays,"weeks"=>$weeks));
	}

	$db = JFactory::getDBO();
	$cID=JRequest::getInt('sid', 0);
	$db->setQuery("INSERT INTO `#__jqcalendar` (`id_student`, `subject`, `starttime`, `endtime`, `isalldayevent`, `description`, `location`, `color`".($rules?", `RecurringRule`":"").")VALUES(".
		$cID.",".
		$db->quote($sub).",".
		$db->quote($this->js2MySqlTime($st)).",".
		$db->quote($this->js2MySqlTime($et)).",".
		$db->quote($ade).",".
		$db->quote($dscr).",".
		$db->quote($loc).",".
		$db->quote($color).
		($rules?",".$db->quote($rules):"").
		")");
	$res=$db->execute();

	if($res)
		return array("IsSuccess"=>true,"Msg"=>'Add: successful',"Data"=>$db->insertid());
	else
		return array("IsSuccess"=>false,"Msg"=>$db->getErrorMsg());
}

function updateDetailedCalendar($cID, $st, $et, $sub, $ade, $dscr, $loc, $color, $tz){
	$isrepeat=JRequest::getInt('repeat', 0);
	$weekdays=JRequest::getVar('wd', array());
	$weekdays=array_map('intval',$weekdays);
	$weeks=JRequest::getVar('w', array());
	$weeks=array_map('intval',$weeks);

	if($isrepeat){
		$rules=json_encode(array("weekdays"=>$weekdays,"weeks"=>$weeks));
	}

	$db = JFactory::getDBO();
	$db->setQuery("UPDATE `#__jqcalendar` SET".
			" `starttime`='" . $this->js2MySqlTime($st) . "',".
			" `endtime`='" . $this->js2MySqlTime($et) . "',".
			" `subject`=" . $db->quote($sub) . ",".
			" `isalldayevent`=" . $db->quote($ade) . ",".
			" `description`=" . $db->quote($dscr) . ",".
			" `location`=" . $db->quote($loc) . ",".
			" `color`=" . $db->quote($color) .
			($rules?", `recurringrule`=" . $db->quote($rules):"").
			" WHERE `id`=" . $cID);
			//echo '<pre>',print_r($db),'</pre>';die;
	$res=$db->execute();

	if($res)
		return array("IsSuccess"=>true,"Msg"=>'Update succefully');
	else
		return array("IsSuccess"=>false,"Msg"=>$db->getErrorMsg());
}

	function removeCalendar($cID){
		$db = JFactory::getDBO();
		$db->setQuery("DELETE FROM `#__jqcalendar` WHERE `id`=" . $cID);
		$res=$db->execute();

		if($res)
				return array("IsSuccess"=>true,"Msg"=>'Succefully');
			else
				return array("IsSuccess"=>false,"Msg"=>$db->getErrorMsg());
	}

}

$controller = JControllerLegacy::getInstance('Datafeed');
$controller->execute(JRequest::getCmd('task'));
$controller->redirect();